package com.ruoyi.ldzlsb.controller;

import java.util.List;
import java.util.Date;
import java.text.SimpleDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.ldzlsb.domain.SbInspectionDateRecord;
import com.ruoyi.ldzlsb.domain.SbInspectionDateDetail;
import com.ruoyi.ldzlsb.domain.SbInspectionRecord;
import com.ruoyi.ldzlsb.service.ISbInspectionDateRecordService;
import com.ruoyi.ldzlsb.service.ISbInspectionDateDetailService;
import com.ruoyi.ldzlsb.service.ISbInspectionRecordService;

/**
 * 巡检日期记录Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/inspection/date-record")
public class SbInspectionDateRecordController extends BaseController
{
    @Autowired
    private ISbInspectionDateRecordService sbInspectionDateRecordService;

    @Autowired
    private ISbInspectionDateDetailService sbInspectionDateDetailService;
    
    @Autowired
    private ISbInspectionRecordService sbInspectionRecordService;
    
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * 查询巡检日期记录列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SbInspectionDateRecord sbInspectionDateRecord)
    {
        startPage();
        List<SbInspectionDateRecord> list = sbInspectionDateRecordService.selectSbInspectionDateRecordList(sbInspectionDateRecord);
        return getDataTable(list);
    }

    /**
     * 获取巡检日期记录详细信息
     */
    @GetMapping(value = "/{recordId}")
    public AjaxResult getInfo(@PathVariable("recordId") Long recordId)
    {
        SbInspectionDateRecord record = sbInspectionDateRecordService.selectSbInspectionDateRecordByRecordId(recordId);
        if (record != null) {
            // 获取巡检日期明细
            List<SbInspectionDateDetail> detailList = sbInspectionDateDetailService.selectSbInspectionDateDetailByDateRecordId(recordId);
            record.setDetailList(detailList);
        }
        return AjaxResult.success(record);
    }

    /**
     * 根据巡检单ID获取巡检日期记录列表
     */
    @GetMapping("/by-record/{inspectionRecordId}")
    public AjaxResult getByInspectionRecord(@PathVariable("inspectionRecordId") Long inspectionRecordId)
    {
        List<SbInspectionDateRecord> list = sbInspectionDateRecordService.selectSbInspectionDateRecordByInspectionRecordId(inspectionRecordId);
        return AjaxResult.success(list);
    }
    
    /**
     * 根据巡检单ID和日期获取巡检日期记录
     */
    @GetMapping("/by-date")
    public AjaxResult getByDate(Long inspectionRecordId, Date inspectionDate)
    {
        logger.info("getByDate - inspectionRecordId: {}, inspectionDate: {}", inspectionRecordId, inspectionDate);
        
        if (inspectionRecordId == null || inspectionDate == null) {
            logger.error("参数错误 - inspectionRecordId: {}, inspectionDate: {}", inspectionRecordId, inspectionDate);
            return AjaxResult.error("参数错误");
        }
        
        try {
            // 使用SimpleDateFormat格式化日期，只保留年月日
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = sdf.format(inspectionDate);
            inspectionDate = sdf.parse(dateStr);
            
            logger.info("格式化后的日期: {}", inspectionDate);
            
            SbInspectionDateRecord record = sbInspectionDateRecordService.selectSbInspectionDateRecordByDate(inspectionRecordId, inspectionDate);
            
            if (record != null) {
                logger.info("找到日期记录: {}", record.getRecordId());
                // 获取巡检日期明细
                List<SbInspectionDateDetail> detailList = sbInspectionDateDetailService.selectSbInspectionDateDetailByDateRecordId(record.getRecordId());
                record.setDetailList(detailList);
                logger.info("获取到明细数量: {}", detailList != null ? detailList.size() : 0);
            } else {
                logger.warn("未找到日期记录");
            }
            
            return AjaxResult.success(record);
        } catch (Exception e) {
            logger.error("获取日期记录异常", e);
            return AjaxResult.error("获取日期记录异常: " + e.getMessage());
        }
    }

    /**
     * 新增巡检日期记录
     */
    @Log(title = "巡检日期记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SbInspectionDateRecord sbInspectionDateRecord)
    {
        return toAjax(sbInspectionDateRecordService.insertSbInspectionDateRecord(sbInspectionDateRecord));
    }

    /**
     * 修改巡检日期记录
     */
    @Log(title = "巡检日期记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SbInspectionDateRecord sbInspectionDateRecord)
    {
        return toAjax(sbInspectionDateRecordService.updateSbInspectionDateRecord(sbInspectionDateRecord));
    }

    /**
     * 删除巡检日期记录
     */
    @Log(title = "巡检日期记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{recordIds}")
    public AjaxResult remove(@PathVariable Long[] recordIds)
    {
        return toAjax(sbInspectionDateRecordService.deleteSbInspectionDateRecordByRecordIds(recordIds));
    }
    
    /**
     * 初始化巡检单的巡检日期记录
     */
    @Log(title = "初始化巡检日期记录", businessType = BusinessType.INSERT)
    @PostMapping("/init/{inspectionRecordId}")
    public AjaxResult init(@PathVariable("inspectionRecordId") Long inspectionRecordId)
    {
        // 获取巡检单
        SbInspectionRecord record = sbInspectionRecordService.selectSbInspectionRecordByRecordId(inspectionRecordId);
        if (record == null) {
            return AjaxResult.error("巡检单不存在");
        }
        
        // 初始化巡检日期记录
        List<SbInspectionDateRecord> dateRecords = sbInspectionDateRecordService.initInspectionDateRecords(record);
        
        return AjaxResult.success(dateRecords);
    }
    
    /**
     * 保存巡检日期结果
     */
    @Log(title = "保存巡检日期结果", businessType = BusinessType.UPDATE)
    @PostMapping("/save-result")
    public AjaxResult saveResult(@RequestBody SbInspectionDateRecord dateRecord)
    {
        if (dateRecord.getRecordId() == null) {
            return AjaxResult.error("参数错误");
        }
        
        // 更新日期记录状态
        dateRecord.setStatus("1"); // 已巡检
        int rows = sbInspectionDateRecordService.updateSbInspectionDateRecord(dateRecord);
        
        // 保存巡检明细
        if (dateRecord.getDetailList() != null && !dateRecord.getDetailList().isEmpty()) {
            sbInspectionDateDetailService.batchSaveDetails(dateRecord.getRecordId(), dateRecord.getDetailList());
        }
        
        // 检查巡检单是否已完成所有日期的巡检
        if (sbInspectionDateRecordService.checkAllDatesCompleted(dateRecord.getInspectionRecordId())) {
            // 更新巡检单状态为已完成
            SbInspectionRecord record = new SbInspectionRecord();
            record.setRecordId(dateRecord.getInspectionRecordId());
            record.setStatus("2"); // 已完成
            record.setEndTime(new Date());
            sbInspectionRecordService.updateSbInspectionRecord(record);
        }
        
        return toAjax(rows);
    }
    
    /**
     * 检查巡检单是否已完成所有日期的巡检
     */
    @GetMapping("/check-completed/{inspectionRecordId}")
    public AjaxResult checkCompleted(@PathVariable("inspectionRecordId") Long inspectionRecordId)
    {
        boolean completed = sbInspectionDateRecordService.checkAllDatesCompleted(inspectionRecordId);
        return AjaxResult.success(completed);
    }
} 